﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.DataProvider.EntityFramework.Repositories {

	public class ForumRepository : Repository<Forum>, IForumRepository {

		public ForumRepository(DbContext context) : base(context) { }

		/// <summary>
		/// Reads the forums that match the specification, including sub forums, latest post, topic and author.
		/// </summary>
		/// <param name="spec"></param>
		/// <returns></returns>
		public IEnumerable<Forum> ReadManyOptimized(ISpecification<Forum> spec) {
			return this.set
				.Include(f => f.SubForums)
				.Include(f => f.LastTopic)
				.Include(f => f.LastPost)
				.Include(f => f.LastPostUser)
				.Where(spec.IsSatisfied);
		}

		/// <summary>
		/// Read one forum that match the specification, including sub forums, latest post, topic and author.
		/// </summary>
		/// <param name="spec"></param>
		/// <returns></returns>
		public Forum ReadOneOptimized(ISpecification<Forum> spec) {
			return this.ReadManyOptimized(spec).FirstOrDefault();
		}

		public override void Delete(Int32 id) {
			Forum f = new Forum { Id = id };
			this.set.Attach(f);
			base.Delete(f);
		}
	}
}